import { NextResponse } from 'next/server';
import { getToken } from 'next-auth/jwt';
import type { NextRequest } from 'next/server';

// 定义公开路由白名单
const publicPaths = [
  '/auth/signin',
  '/auth/signup',
  '/api/auth/signin',
  '/api/auth/signup',
  '/api/auth/callback',
  '/api/auth/session',
  '/api/auth/providers',
  '/api/auth/csrf',
];

export async function middleware(request: NextRequest) {
  const { pathname } = request.nextUrl;

  // 检查是否是公开路由
  if (publicPaths.some(path => pathname.startsWith(path))) {
    return NextResponse.next();
  }

  // 检查是否是API路由
  if (pathname.startsWith('/api/')) {
    // API路由返回401状态码
    const token = await getToken({ req: request });
    if (!token) {
      return NextResponse.json(
        { error: '未授权访问' },
        { status: 401 }
      );
    }
    return NextResponse.next();
  }

  // 检查用户是否已认证
  const token = await getToken({ req: request });
  if (!token) {
    // 保存当前URL作为重定向回调
    const callbackUrl = encodeURIComponent(request.url);
    return NextResponse.redirect(
      new URL(`/auth/signin?callbackUrl=${callbackUrl}`, request.url)
    );
  }

  return NextResponse.next();
}

// 配置中间件匹配的路由
export const config = {
  matcher: ['/((?!_next/static|_next/image|favicon.ico).*)'],
};